<script lang="ts" setup>
import { reactive, ref, computed,watch } from 'vue'
import  * as XLSX from 'xlsx'
import {ElMessage} from "element-plus";

const dialogVisible = ref(false)
const isEdit = ref(false)
const editIndex = ref(-1)
const pageSize = ref(10)
const currentPage = ref(1)
const importDialog = ref(false)
const importFile = ref(null)
const searchResults = ref([])
const isSearching = ref(false)
/**
 * 表格数据初始化
 *
 * @description 初始化用于展示的模拟招聘者列表数据。
 * 包含字段如 ID、姓名、应聘岗位、应聘状态等基本信息。
 */
const tableData = reactive([
  {
    id: 1,
    name: '小伟',
    post: '客户经理',
    status: '已筛选',
    section: '人力资源中心	',
    requirement: '客户经理招聘',
    sex: '男',
    age: '26',
    background: '本科',
    time:'2023-06-15 14:45:00'
  }, {
    id: 2,
    name: '小薇',
    post: '客户经理',
    status: '已筛选',
    section: '人力资源中心	',
    requirement: '客户经理招聘',
    sex: '女',
    age: '24',
    background: '本科',
    time:'2023-06-15 14:45:00'
  }, {
    id: 3,
    name: '小聪',
    post: '客户经理',
    status: '已筛选',
    section: '人力资源中心	',
    requirement: '客户经理招聘',
    sex: '男',
    age: '24',
    background: '本科',
    time:'2023-06-15 14:45:00'
  }, {
    id: 4,
    name: '小燕',
    post: '客户经理',
    status: '已筛选',
    section: '人力资源中心	',
    requirement: '客户经理招聘',
    sex: '女',
    age: '24',
    background: '本科',
    time:'2023-06-15 14:45:00'
  },
])
interface ImportData {
  name?: string;
  姓名?: string;
  post?: string;
  应聘岗位?: string;
  status?: string;
  应聘状态?: string;
  section?: string;
  招聘部门?: string;
  requirement?: string;
  所属招聘需求?: string;
  sex?: string;
  性别?: string;
  age?: string | number;
  年龄?: string | number;
  background?: string;
  学历?: string;
  time?: string;
  入职时间?: string;
}
const searchForm = reactive({
  name: '',
  post: '',
  status: '',
  section: '',
  sex: '',
  age: '',
  background: '',
})
const form = reactive({
  name: '',
  post: '',
  status: '',
  section: '',
  requirement: '',
  sex: '',
  age: '',
  background: '',
  time: ''
})

const showImportDialog = () => {
  importDialog.value = true
}
/*const handleFileUpload = (event: Event) => {
  const input = event.target as HTMLInputElement;
  const file = input.files?.[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      const data = new Uint8Array(e.target!.result as ArrayBuffer);
      const workbook = XLSX.read(data, { type: 'array' });
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];
      const jsonData: ImportData[] = XLSX.utils.sheet_to_json(worksheet);


      jsonData.forEach((item) => {
        const newRow = {
          id: tableData.length + 1,
          name: item.name ?? item.姓名 ?? '',
          post: item.post ?? item.应聘岗位 ?? '',
          status: item.status ?? item.应聘状态 ?? '',
          section: item.section ?? item.招聘部门 ?? '',
          requirement: item.requirement ?? item.所属招聘需求 ?? '',
          sex: item.sex ?? item.性别 ?? '',
          age: String(item.age ?? item.年龄 ?? ''),
          background: item.background ?? item.学历 ?? '',
          time: item.time ?? item.入职时间 ?? ''
        };
        tableData.push(newRow);
      });

      importDialog.value = false;
      input.value = ''; // 清空文件选择器
    } catch (error) {
      console.error('文件解析错误:', error);
    }
  };

  reader.readAsArrayBuffer(file);
};*/
const batchImportDialogVisible = ref(false)
const batchImportFile = ref(null)
function handleBatchImport() {
  //ElMessage.success('导入成功')
  batchImportDialogVisible.value = true
}
function handleBatchFileUpload(){
  batchImportDialogVisible.value = false
  batchImportFile.value?.submit();
  ElMessage.success('批量导入成功')
}
const handleApplyFileUpload= (file)=>{
  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      const  result = e.target?.result;
      if (!(result instanceof  ArrayBuffer)){
        ElMessage.error('文件读取失败，数据格式不正确');
        return;
      }
      const data = new Uint8Array(result);
      const workbook = XLSX.read(data, { type: 'array' });
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];
      const jsonData: ImportData[] = XLSX.utils.sheet_to_json(worksheet);
      jsonData.forEach((item) => {
        const newRow = {
          id: tableData.length + 1,
          name: item.name ?? item.姓名 ?? '',
          post: item.post ?? item.应聘岗位 ?? '',
          status: item.status ?? item.应聘状态 ?? '',
          section: item.section ?? item.招聘部门 ?? '',
          requirement: item.requirement ?? item.所属招聘需求 ?? '',
          sex: item.sex ?? item.性别 ?? '',
          age: String(item.age ?? item.年龄 ?? ''),
          background: item.background ?? item.学历 ?? '',
          time: item.time ?? item.入职时间 ?? ''
        };
        tableData.push(newRow);
      });
      importDialog.value = false;
      ElMessage.success('批量导入成功');
    }catch (error){
      console.error('文件解析错误:', error);
      ElMessage.error('文件解析失败，请检查文件格式');
    }
  };
  reader.readAsArrayBuffer(file.raw);
}
const downloadApplyTemplate = () => {
  try {
    const templateData = [
      {
        '姓名': '',
        '应聘岗位': '',
        '应聘状态': '',
        '招聘部门': '',
        '所属招聘需求': '',
        '性别': '',
        '年龄': '',
        '学历': '',
        '入职时间': ''
      }
    ]
    const worksheet = XLSX.utils.json_to_sheet(templateData)
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, '应聘者信息模版')
    //XLSX.writeFile(workbook, '应聘者信息模版.xlsx')
    const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = '应聘者信息模版.xlsx';
    link.click();
    URL.revokeObjectURL(url);
  }catch (error){
    console.error('下载模板失败:', error);
    ElMessage.error('下载模板失败');
  }
}
const paginatedTableData = computed(() => {
  const data = filterTableData.value
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return data.slice(start, end)
})
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}
const handleCurrentChange = (val) => {
  currentPage.value = val
}

const showDialog = () => {
  isEdit.value= false
  Object.keys(form).forEach(key => {
    form[key] = ''
  })
  dialogVisible.value = true
}
const showEditDialog = (row,index) => {
  isEdit.value = true
  editIndex.value = index
  Object.keys(form).forEach(key => {
    form[key] = row[key]
  })
  dialogVisible.value = true
}
const deleteRow = (index) => {
  tableData.splice(index,1)
}
const submitForm = () => {
  //console.log('提交表单',form)
  if (isEdit.value){
    Object.keys(form).forEach(key => {
      tableData[editIndex.value][key] = form[key]
    })
  }else {
    const  newRow = {...form, id:tableData.length+1}
    tableData.push(newRow)
  }
  dialogVisible.value = false
}
const cancelForm = () => {
  dialogVisible.value = false
}
const  filterTableData = computed(() =>{
  if (isSearching.value){
    return searchResults.value
  }
  return tableData
})
const handleSearch = () => {
  const hasSearchCriteria = Object.values(searchForm).some(value => value !== '')
  if (!hasSearchCriteria){
    isSearching.value= false
    searchResults.value = []
    currentPage.value = 1
    return
  }
  isSearching.value = true
  searchResults.value = tableData.filter(item => {
    if (searchForm.name && !item.name.includes(searchForm.name)){
      return false
    }
    if (searchForm.post && item.post !== searchForm.post){  // 修复这一行
      return false
    }
    if (searchForm.status && item.status !== searchForm.status){
      return false
    }
    if (searchForm.sex && item.sex !== searchForm.sex){
      return false
    }
    if (searchForm.background && item.background !== searchForm.background){
      return false
    }
    if (searchForm.section && item.section !== searchForm.section){
      return false
    }
    if (searchForm.age && item.age !== searchForm.age){
      return false
    }
    return true
  })
  currentPage.value = 1
}
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  isSearching.value = false
  searchResults.value = []
  currentPage.value = 1
}
watch(
    () => ({ ...searchForm}),
    () => {
      handleSearch()
    },
    { deep: true }
)
</script>

<!-- 招聘者信息 -->
<template>
    <div class="container">
        <!-- 使用 Element Plus 的卡片组件展示整体内容区域 -->
        <el-card shadow="always" class="main-card">
            <!-- 标题部分 -->
            <div class="header-section">
                <span class="title">招聘者信息</span>
            </div>
            <!-- 搜索功能区：输入框与搜索按钮 -->
            <div class="search-section">
                    <el-input v-model="searchForm.name" placeholder="请输入姓名"  clearable/>
                    <el-select v-model="searchForm.post" placeholder="请选择应聘岗位" clearable>
                      <el-option label="客户经理" value="客户经理"></el-option>
                      <el-option label="销售经理" value="销售经理"></el-option>
                      <el-option label="销售人员" value="销售人员"></el-option>
                      <el-option label="开发人员" value="开发人员"></el-option>
                      <el-option label="测试人员" value="测试人员"></el-option>
                      <el-option label="其他" value="其他"></el-option>
                    </el-select>
                    <el-select v-model="searchForm.status" placeholder="请选择应聘状态" clearable>
                      <el-option label="待筛选" value="待筛选"></el-option>
                      <el-option label="待面试" value="待面试"></el-option>
                      <el-option label="待入职" value="待入职"></el-option>
                      <el-option label="入职" value="入职"></el-option>
                      <el-option label="拒绝" value="拒绝"></el-option>
                      <el-option label="待转正" value="待转正"></el-option>
                      <el-option label="转正" value="转正"></el-option>
                      <el-option label="离职" value="离职"></el-option>
                      <el-option label="待离职" value="待离职"></el-option>
                    </el-select>
                    <el-select v-model="searchForm.sex" placeholder="请选择性别" clearable>
                      <el-option label="男" value="男"></el-option>
                      <el-option label="女" value="女"></el-option>
                      <el-option label="未知" value="未知"></el-option>
                    </el-select>
                    <el-select v-model="searchForm.background" placeholder="请选择学历" clearable>
                      <el-option label="研究生" value="研究生"></el-option>
                      <el-option label="本科" value="本科"></el-option>
                      <el-option label="大专" value="大专"></el-option>
                      <el-option label="高中" value="高中"></el-option>
                      <el-option label="初中" value="初中"></el-option>
                      <el-option label="小学" value="小学"></el-option>
                      <el-option label="其他" value="其他"></el-option>
                    </el-select>
                    <el-select v-model="searchForm.section" placeholder="请选择部门" clearable>
                      <el-option label="销售部" value="销售部"></el-option>
                      <el-option label="开发部" value="开发部"></el-option>
                      <el-option label="测试部" value="测试部"></el-option>
                      <el-option label="财务部" value="财务部"></el-option>
                      <el-option label="HR部" value="HR部"></el-option>
                      <el-option label="行政部" value="行政部"></el-option>
                      <el-option label="其他" value="其他"></el-option>
                    </el-select>
                    <el-input v-model="searchForm.age" placeholder="请输入年龄" clearable/>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="resetSearch">重置</el-button>
              </div>
            <!-- 功能按钮区：批量导入和新增应聘者 -->
            <div class="action-buttons">
                <el-button type="info" @click="showImportDialog">批量导入</el-button>
                <el-button @click="showDialog">录入应聘者</el-button>
            </div>

            <!-- 表格数据展示区 -->
          <div class="table-wrapper">
            <el-table 
                :data="paginatedTableData"
                border 
                style="width: 100%" 
                :header-cell-style="{ textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }"
                class="apply-table"
            >
                <!-- 序号列 -->
                <el-table-column prop="id" label="序号" width="60"/>
                <!-- 姓名列 -->
                <el-table-column prop="name" label="姓名" min-width="80"/>
                <!-- 应聘岗位列 -->
                <el-table-column prop="post" label="应聘岗位" min-width="100"/>
                <!-- 应聘状态列 -->
                <el-table-column prop="status" label="应聘状态" min-width="80"/>
                <!-- 招聘部门列 -->
                <el-table-column prop="section" label="招聘部门" min-width="100"/>
                <!-- 所属招聘需求列 -->
                <el-table-column prop="requirement" label="所属招聘需求" min-width="120"/>
                <!-- 性别列 -->
                <el-table-column prop="sex" label="性别" width="60"/>
                <!-- 年龄列 -->
                <el-table-column prop="age" label="年龄" width="60"/>
                <!-- 学历列 -->
                <el-table-column prop="background" label="学历" min-width="80"/>
                <!-- 登记时间列 -->
                <el-table-column prop="time" label="入职时间" width="140"/>
                <!-- 操作列 -->
                <el-table-column label="操作" fixed="right" width="80">
                    <template #default="scope">
                      <el-button type="primary" size="small" @click="showEditDialog(scope.row, scope.$index)" >编辑</el-button>
                      <el-button type="danger" size="small" @click="deleteRow(scope.$index)" >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
          </div>
            <!-- 分页控件 -->
            <div class="pagination-wrapper">
                <el-pagination 
                    size="small" 
                    background
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="filterTableData.length"
                    :page-sizes="[10, 20, 50, 100]"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    class="mt-4" 
                />
            </div>
        </el-card>
      <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑应聘者' : '新增应聘者'" width="500px">
        <el-form :model="form" label-width="100px">
          <el-form-item label="姓名">
            <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item label="应聘岗位">
            <el-select v-model="form.post" placeholder="请选择应聘岗位">
              <el-option label="客户经理" value="客户经理"></el-option>
              <el-option label="销售经理" value="销售经理"></el-option>
              <el-option label="销售人员" value="销售人员"></el-option>
              <el-option label="开发人员" value="开发人员"></el-option>
              <el-option label="测试人员" value="测试人员"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="应聘状态">
            <el-select v-model="form.status" placeholder="请选择应聘状态">
              <el-option label="待筛选" value="待筛选"></el-option>
              <el-option label="待面试" value="待面试"></el-option>
              <el-option label="待入职" value="待入职"></el-option>
              <el-option label="待转正" value="待转正"></el-option>
              <el-option label="待离职" value="待离职"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="招聘部门">
            <el-select v-model="form.section" placeholder="请选择招聘部门">
              <el-option label="人力资源部" value="人力资源部"></el-option>
              <el-option label="销售部" value="销售部"></el-option>
              <el-option label="财务部" value="财务部"></el-option>
              <el-option label="开发部" value="开发部"></el-option>
              <el-option label="测试部" value="测试部"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属招聘需求">
            <el-input v-model="form.requirement" placeholder="请输入所属招聘需求"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="form.sex" placeholder="请选择性别">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
              <el-option label="未知" value="未知"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年龄">
            <el-input-number v-model="form.age" placeholder="请输入年龄"></el-input-number>
          </el-form-item>
          <el-form-item label="学历">
            <el-select v-model="form.background" placeholder="请选择学历">
              <el-option label="研究生" value="研究生"></el-option>
              <el-option label="本科" value="本科"></el-option>
              <el-option label="大专" value="大专"></el-option>
              <el-option label="高中" value="高中"></el-option>
              <el-option label="初中" value="初中"></el-option>
              <el-option label="小学" value="小学"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="入职时间">
            <el-date-picker v-model="form.time" type="date" placeholder="请选择入职时间"></el-date-picker>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogVisible = false">确定</el-button>
        </template>
    </el-dialog>

      <el-dialog v-model="importDialog" title="批量导入应聘者" width="500px">
        <el-alert
            title="请按照模板格式准备数据，支持.xls和.xlsx格式文件"
            type="info"
            show-icon
            style="margin-bottom: 20px;"
            disabled
            :closable="false"
        />
        <el-upload
            class="upload-demo"
            drag
            action="#"
            :auto-upload="false"
            :on-change="handleApplyFileUpload"
            accept=".xls,.xlsx"
            ref="batchImportFile"
        >
          <el-icon class="el-icon--upload">
            <upload-filled />
          </el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              请上传Excel格式文件，确保包含应聘者信息字段
            </div>
          </template>
        </el-upload>
        <div class="import-actions">
          <el-link @click="downloadApplyTemplate" type="primary" >
            下载模板
          </el-link>
        </div>
        <div style="margin-top: 15px; font-size: 14px; color: #666;">
          <p><strong>导入说明：</strong></p>
          <p>1. 点击"下载模板"获取标准格式文件</p>
          <p>2. 按照模板格式填写应聘者信息</p>
          <p>3. 点击"选择文件"上传填写好的文件</p>
          <p>4. 系统将自动解析并导入数据</p>
        </div>
          <template #footer>
      <span class="dialog-footer">
        <el-button @click="batchImportDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBatchFileUpload">确定导入</el-button>
      </span>
          </template>
      </el-dialog>
    </div>
</template>
 
<style scoped>
.header-section{
  margin-bottom: 20px;
}
.title{
  font-size: 20px;
  font-weight: bold;
}
</style>
